<template>
  <div class="app-container flex-cloumn">
    <!--  操作 模糊搜素  -->
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch">
      <el-row :gutter="12">
        <el-col :span="4">
          <el-form-item label="商品" prop="iCode">
            <marketBaseCombox url="/marketdata/tcmdtController/queryTcmdtInfoByPage.action"
                        ref="cfgIdRef"
                        prop="iCode"
                        clearable
                        valueField="iCode"
                        labelField="instrument"
                        size="small"
                        :style="{width: '100%'}"
                        placeholder="商品" v-model="queryParams.iCode"></marketBaseCombox>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="开始日期">
            <el-date-picker
                v-model="queryParams.begDate"
                type="date"
                :style="{width: '100%'}"
                :disabled-date="disabledDateBeg"
                size="small"
                value-format="YYYY-MM-DD"
                placeholder="选择开始日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="结束日期">
            <el-date-picker
                v-model="queryParams.endDate"
                type="date"
                :style="{width: '100%'}"
                :disabled-date="disabledDateEnd"
                size="small"
                value-format="YYYY-MM-DD"
                placeholder="选择结束日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-button type="primary" icon="Search" size="small" style="margin: 3px 3px"
            v-hasPermi="['marketdata:commodity:commodityPrice:list']"  @click="handleQuery">搜索
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <!--  按钮  -->
      <el-row :gutter="12" style="margin: 0px 1px">
        <el-form-item>
          <el-button type="success" icon="Edit" size="small"
                     style="margin: 3px 3px"
                     v-hasPermi="['marketdata:commodity:commodityPrice:update']"
                     :disabled="single" @click="handleUpdate">修改
          </el-button>
<!--          <el-button-->
<!--              type="warning"-->
<!--              style="margin: 3px 3px"-->
<!--              icon="Download"-->
<!--              size="small"-->
<!--              @click="handleExport"-->
<!--              v-hasPermi="['marketdata:commodity:commodityPrice:exportPrice']"-->
<!--          >当页导出-->
<!--          </el-button>-->
          <el-button
              type="warning"
              style="margin: 3px 3px"
              icon="Download"
              size="small"
              @click="handleExportAll"
              v-hasPermi="['marketdata:commodity:commodityPrice:exportPrice']"
          >导出
          </el-button>
        </el-form-item>
      </el-row>

    </el-form>
    <xTable ref="cmdtRef" v-loading="loading" :data="cmdtList" multiple="false" class="tableDragger_form"
            refId="cmdtRef" @selection-change="handleSelectionChange">
      <template #columList>
        <el-table-column label="序号" type="index" width="40"></el-table-column>
        <el-table-column label="日期" align="center" prop="begDate" :show-overflow-tooltip="true"/>
        <el-table-column label="代码" width="80" show-overflow-tooltip>
          <template #default="scope">
            <el-link type="primary" @click="queryTrade(scope.row.iCode,scope.row.aType,scope.row.mType)">
              {{ scope.row.iCode }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="名称" align="left" :show-overflow-tooltip="true" prop="sName"></el-table-column>
        <el-table-column label="资产类型" align="center" prop="aType" :show-overflow-tooltip="true">
          <template #default="scope">
            <dict-tag :options="A_TYPE" :value="scope.row.aType"/>
          </template>
        </el-table-column>
        <el-table-column label="市场类型" align="center" prop="mType" :show-overflow-tooltip="true">
          <template #default="scope">
            <dict-tag :options="M_TYPE" :value="scope.row.mType"/>
          </template>
        </el-table-column>
        <el-table-column label="开盘价" align="right" :show-overflow-tooltip="true" prop="dpOpen"
                         :formatter="formartTableP2"></el-table-column>
        <el-table-column label="收盘价" align="right" :show-overflow-tooltip="true" prop="dpClose"
                         :formatter="formartTableP2"></el-table-column>
        <el-table-column label="最高价" align="right" :show-overflow-tooltip="true" prop="dpHigh"
                         :formatter="formartTableP2"></el-table-column>
        <el-table-column label="最低价" align="right" :show-overflow-tooltip="true" prop="dpLow"
                         :formatter="formartTableP2"></el-table-column>
        <el-table-column label="最新价" align="right" :show-overflow-tooltip="true" prop="tradePrice"
                         :formatter="formartTableP2"></el-table-column>
      </template>
    </xTable>

    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    <!--修改对话框 -->
    <el-dialog :title="cmdtTitle" v-model="UpdateOpen" width="500px" :close-on-click-modal="false" draggable
               destroy-on-close append-to-body>
      <el-form ref="cmdtFromRef" :model="cmdtFrom" :rules="cmdtRules" label-width="110px">
        <el-form-item label="日期" prop="begDate">
          <el-input disabled v-model="cmdtFrom.begDate"/>
        </el-form-item>
        <el-form-item label="合约代码" prop="iCode">
          <el-input disabled v-model="cmdtFrom.iCode"/>
        </el-form-item>
        <el-form-item label="合约名称" prop="sName">
          <el-input disabled v-model="cmdtFrom.sName"/>
        </el-form-item>
        <el-form-item label="市场类型" prop="mType">
          <dictCombox v-model="cmdtFrom.mType" dictType="M_TYPE" prop="mType"
                      disabled
                      size="small"></dictCombox>
        </el-form-item>
        <el-form-item label="资产类型" prop="aType">
          <dictCombox v-model="cmdtFrom.aType" dictType="A_TYPE" prop="aType"
                      disabled
                      size="small"></dictCombox>
        </el-form-item>
        <el-form-item label="开盘价" prop="dpOpen">
          <number v-model="data.cmdtFrom.dpOpen" maxlength="12" precision="4"></number>
        </el-form-item>
        <el-form-item label="收盘价" prop="dpClose">
          <number v-model="data.cmdtFrom.dpClose" maxlength="12" precision="4"></number>
        </el-form-item>
        <el-form-item label="最高价" prop="dpHigh">
          <number v-model="data.cmdtFrom.dpHigh" maxlength="12" precision="4"></number>
        </el-form-item>
        <el-form-item label="最低价" prop="dpLow">
          <number v-model="data.cmdtFrom.dpLow" maxlength="12" precision="4"></number>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submit">确 定</el-button>
          <el-button @click="cancelUpdate">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CommodityPrice">
import {getCmdtPriceList, updateTcmdtPrice} from '@/api/marketdata/commodity/commodity';
import {getLastWorkDay} from '@/api/marketdata/equity/fund';

const router = useRouter();
import xTable from "@/xquant/base/xTable";
import InputAmount from '@/xquant/base/InputAmount'
const {proxy} = getCurrentInstance();
const {M_TYPE} = proxy.useDict("M_TYPE");
const {A_TYPE} = proxy.useDict("A_TYPE");
const {CURRENCY} = proxy.useDict("CURRENCY");
import number from '@/xquant/base/number';
import marketBaseCombox from "@/xquant/base/marketBaseCombox";
const cmdtList = ref([]);
const open = ref(false);
const UpdateOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const rows = ref([]);
const indexs = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const cmdtTitle = ref("");
const instrument = ref("");
const data = reactive({
  cmdtRules: {
    dpOpen: [{required: false, message: "  ", trigger: "change"}],
    dpClose: [{required: true, message: "收盘价不能为空 ", trigger: "change"}, {
      validator: (rule, value, callback) => {
        return Number(value) > 0
      }, message: ' ', trigger: 'change'
    }],
    dpHigh: [{required: false, message: "最高价不能为空 ", trigger: "change"}],
    dpLow: [{required: false, message: "最低价不能为空 ", trigger: "change"}],
    dpAvg: [{required: false, message: "平均价不能为空 ", trigger: "change"}],
    dpSet: [{required: false, message: "结算价不能为空 ", trigger: "change"}],
  },
  cmdtFrom: {},
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    instrument: undefined,
    begDate: undefined,
    endDate: proxy.$moment(new Date()).format("YYYY-MM-DD"),
  }
});

onMounted(() => {
  if (proxy.isNotVoid(router.currentRoute.value.query)) {
    queryParams.value.begDate = router.currentRoute.value.query.begDate
    queryParams.value.endDate = proxy.$moment(queryParams.value.begDate).add(1,"days").format("YYYY-MM-DD");
  } else {
    getLastWorkDay().then(response => {
      queryParams.value.begDate = response.msg
      getList()
    })
  }
})

const disabledDateBeg = (time) => {
  if (queryParams.value.endDate) {
    return time.getTime() > new Date(queryParams.value.endDate).getTime()
  }
}

const disabledDateEnd = (time) => {
  if (queryParams.value.begDate) {
    return time.getTime() < new Date(queryParams.value.begDate).getTime() - 86400000
  }
}

const {queryParams, selectDate, cmdtFrom, cmdtRules} = toRefs(data);

/** 导出按钮操作 */
function handleExport() {
  proxy.download("marketdata/tcmdtController/exportPrice", {
    ...queryParams.value
  }, `商品行情${new Date().getTime()}.xlsx`);
}

/** 导出按钮操作 */
function handleExportAll() {
  proxy.download("marketdata/tcmdtController/exportPrice", Object.assign({
    ...queryParams.value
  }, {pageNum: '', pageSize: ''}), `商品行情${new Date().getTime()}.xlsx`);
}

/** 查询列表 */
function getList() {
  loading.value = true;
  if (typeof(queryParams.value.iCode) !== 'undefined') {

  } else {
    if (proxy.isNotVoid(router.currentRoute.value.query)) {
      queryParams.value.iCode = router.currentRoute.value.query.iCode
    }
  }
  getCmdtPriceList(queryParams.value).then(response => {
    cmdtList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value.pageNum = 1;
  queryParams.value.iCode = null;
  queryParams.value.begDate = null;
  queryParams.value.endDate = null;
  getList();
}

// 修改
function handleUpdate() {
  reset();
  UpdateOpen.value = true;
  cmdtFrom.value = Object.assign({},rows.value[0]);
  cmdtTitle.value = "修改商品行情";
}

// 重置表单
function reset() {
  cmdtFrom.value = {};
  proxy.resetForm("cmdtFromRef");
}

function submit() {
   proxy.$refs["cmdtFromRef"].validate((valid) => {
    if (valid) {
      UpdateOpen.value = false;
      updateTcmdtPrice(cmdtFrom.value).then(response => {
        if (response.success) {
          proxy.$modal.msgSuccess("修改成功");
          reset();
          getList();
        } else {
          proxy.$modal.msgError(response.msg);
        }
      });
      reset()
    }
  })
}

// 多选框选中
function handleSelectionChange(selection) {
  if (selection.length == 0) {
    ids.value = [];
    indexs.value = [];
    rows.value = [];
  } else {
    ids.value = selection.map(item => item.iCode);
    indexs.value = selection.map(item => item.index);
    rows.value = selection.map(item => item);
  }
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  if (selection.length == 1) {
    single.value = false;
  }
  if (selection.length != 1) {
    single.value = true;
  }
}

/**
 * 根据代码查询交易
 * */
function queryTrade(iCode, a, m) {
  instrument.value = iCode + ',' + a + ',' + m
  router.push({
    path: "/TradeManage/tradeBalance",
    query: {"instrument": instrument.value},
  });
}

/** 取消修改按钮 */
function cancelUpdate() {
  UpdateOpen.value = false;
  reset();
}

</script>

<style scoped>
.el-link {
  margin-right: 8px;
}

.el-link .el-icon--right.el-icon {
  vertical-align: text-bottom;
}
</style>
